<template>
  <div class="feedback-container">
    <div class="feedback-header">
      <h2>评价管理</h2>
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索评价内容"
          clearable
          @clear="loadFeedbacks"
          style="width: 300px"
        >
          <template #append>
            <el-button @click="loadFeedbacks">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
    </div>

    <div class="feedback-list" v-loading="loading" element-loading-text="加载中...">
      <el-empty v-if="!loading && feedbackList.length === 0" description="暂无评价"></el-empty>
      <el-card v-for="feedback in feedbackList" :key="feedback.id" class="feedback-card">
        <div class="feedback-header">
          <div class="order-info">
            <span class="order-number">订单号：{{ feedback.orderNumber || '未关联订单' }}</span>
            <span class="feedback-time">评价时间：{{ formatDateTime(feedback.createTime) }}</span>
          </div>
          <div class="rating">
            <el-rate v-model="feedback.rating" disabled></el-rate>
          </div>
        </div>
        <div class="feedback-content">
          <div class="feedback-text">{{ feedback.content }}</div>
        </div>
      </el-card>

      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const searchKeyword = ref('')

// 评价列表
const feedbackList = ref<any[]>([])

// 加载评价列表
const loadFeedbacks = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value || undefined
    }

    const response = await axios.get('/feedback/merchant', { params })

    if (response.data.code === 1) {
      feedbackList.value = response.data.data.records || []
      total.value = response.data.data.total || 0

      // 如果后端没有返回总数，但有返回记录，则使用记录数量作为总数
      if (total.value === 0 && feedbackList.value.length > 0) {
        total.value = feedbackList.value.length
      }

      // 处理订单号
      for (const feedback of feedbackList.value) {
        if (feedback.orderId) {
          try {
            const orderRes = await axios.get(`/order/detail/${feedback.orderId}`)
            if (orderRes.data.code === 1) {
              feedback.orderNumber = orderRes.data.data.number
            } else {
              feedback.orderNumber = `订单ID: ${feedback.orderId}`
            }
          } catch (error) {
            console.error(`获取订单${feedback.orderId}详情失败:`, error)
            feedback.orderNumber = `订单ID: ${feedback.orderId}`
          }
        } else {
          feedback.orderNumber = '未关联订单'
        }
      }
    } else {
      ElMessage.error(response.data.msg || '获取评价列表失败')
    }
  } catch (error) {
    console.error('获取评价列表失败:', error)
    ElMessage.error('获取评价列表失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadFeedbacks()
}

// 当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadFeedbacks()
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return '';

  try {
    const date = new Date(dateTimeStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
  } catch (error) {
    console.error('日期格式化错误:', error);
    return dateTimeStr;
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadFeedbacks()
})
</script>

<style scoped>
.feedback-container {
  padding: 20px;
}

.feedback-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.feedback-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.feedback-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.order-number {
  font-weight: bold;
  margin-right: 20px;
}

.feedback-time {
  color: #409EFF;
  font-weight: 500;
  margin-left: 15px;
}

.feedback-content {
  margin-bottom: 15px;
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
}

.feedback-text {
  line-height: 1.6;
  color: #333;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
